package com.gh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gh.common.exception.Assert;
import com.gh.common.exception.BusinessException;
import com.gh.common.result.ResponseEnum;
import com.gh.common.util.MD5;
import com.gh.entity.UserAccount;
import com.gh.entity.UserInfo;
import com.gh.entity.UserLoginRecord;
import com.gh.mapper.UserAccountMapper;
import com.gh.mapper.UserInfoMapper;
import com.gh.mapper.UserLoginRecordMapper;
import com.gh.query.UserInfoQuery;
import com.gh.service.UserAccountService;
import com.gh.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gh.utils.JwtUtils;
import com.gh.vo.LoginVo;
import com.gh.vo.RegisterVo;
import com.gh.vo.UserIndexVo;
import com.gh.vo.UserInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author Eric
 * @since 2021-09-06
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserAccountMapper accountMapper;

    @Autowired
    private UserLoginRecordMapper userLoginRecordMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(RegisterVo registerVo) {
        //判断用户是否已经被注册
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getMobile, registerVo.getMobile());
        Integer count = baseMapper.selectCount(lambdaQueryWrapper);
        Assert.isTrue(count == 0, ResponseEnum.MOBILE_EXIST_ERROR);
        //插入用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserType(registerVo.getUserType());
        userInfo.setName(registerVo.getMobile());
        userInfo.setNickName(registerVo.getMobile());
        userInfo.setMobile(registerVo.getMobile());
        userInfo.setPassword(MD5.encrypt(registerVo.getPassword()));
        userInfo.setStatus(UserInfo.STATUS_NORMAL);
        userInfo.setHeadImg("https://eric123.oss-cn-shanghai.aliyuncs.com/2021/05/19/cover/6fc26885-d01b-4663-9cfb-cbf6e1ce3c13b21c8701a18b87d6277fd470b5403f381f30e9245701.jpg?versionId=CAEQIRiBgMCPjcKUzBciIDcxYmQxNGFmZTA5ZjQyMmVhZGVlMWU1MDUwMWZiNjdj");
        int insert = baseMapper.insert(userInfo);
        if (insert > 0) {
            //插入用户账户记录
            UserAccount userAccount = new UserAccount();
            userAccount.setUserId(userInfo.getId());
            accountMapper.insert(userAccount);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserInfoVo login(LoginVo loginVo, String ip) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        Integer userType = loginVo.getUserType();
        //用户是否存在
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getMobile, mobile).eq(UserInfo::getUserType, userType);
        UserInfo userInfo = baseMapper.selectOne(lambdaQueryWrapper);
        if (userInfo == null) {
            throw new BusinessException(ResponseEnum.LOGIN_MOBILE_ERROR);
        }
        //密码是否正确
        if (!userInfo.getPassword().equals(MD5.encrypt(password))) {
            throw new BusinessException(ResponseEnum.LOGIN_PASSWORD_ERROR);
        }
        //用户是否被禁用
        if (userInfo.getStatus().intValue() == UserInfo.STATUS_LOCKED.intValue()) {
            throw new BusinessException(ResponseEnum.LOGIN_LOKED_ERROR);
        }
        //记录登录日志
        UserLoginRecord userLoginRecord = new UserLoginRecord();
        userLoginRecord.setUserId(userInfo.getId());
        userLoginRecord.setIp(ip);
        userLoginRecord.setDeleted(false);
        userLoginRecordMapper.insert(userLoginRecord);
        //生成token
        String token = JwtUtils.createToken(userInfo.getId(), userInfo.getName());
        //组装userInfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        userInfoVo.setToken(token);
        return userInfoVo;
    }

    @Override
    public IPage<UserInfo> selectListPage(UserInfoQuery userInfoQuery, Page<UserInfo> pageParam) {
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (userInfoQuery == null) {
            return baseMapper.selectPage(pageParam, null);
        }
        if (StringUtils.isNotBlank(userInfoQuery.getMobile())) {
            lambdaQueryWrapper.eq(UserInfo::getMobile, userInfoQuery.getMobile());
        }
        if (userInfoQuery.getStatus() != null) {
            lambdaQueryWrapper.eq(UserInfo::getStatus, userInfoQuery.getStatus());
        }
        if (userInfoQuery.getUserType() != null) {
            lambdaQueryWrapper.eq(UserInfo::getUserType, userInfoQuery.getUserType());
        }
        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, lambdaQueryWrapper);
        return userInfoPage;
    }

    @Override
    public void lock(Long id, Integer status) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setStatus(status);
        baseMapper.updateById(userInfo);
    }

    @Override
    public boolean checkMobile(String mobile) {
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getMobile, mobile);
        Integer count = baseMapper.selectCount(lambdaQueryWrapper);
        return count > 0 ? true : false;
    }

    @Override
    public UserIndexVo getIndexUserInfo(Long userId) {
        UserIndexVo userIndexVo = new UserIndexVo();
        UserInfo userInfo = baseMapper.selectById(userId);
        BeanUtils.copyProperties(userInfo, userIndexVo);
        userIndexVo.setUserId(userId);
        UserAccount userAccount = accountMapper.selectAccountByUserId(userId);
        userIndexVo.setAmount(userAccount.getAmount());
        userIndexVo.setFreezeAmount(userAccount.getFreezeAmount());
        List<UserLoginRecord> list = userLoginRecordMapper.findLastLoginTime(userId);
        if (list.size() >= 2) {
            Date lastLoginTime = list.get(1).getCreateTime();
            userIndexVo.setLastLoginTime(lastLoginTime);
        } else {
            userIndexVo.setLastLoginTime(list.get(0).getCreateTime());
        }
        return userIndexVo;
    }

    @Override
    public String getMobileByBindCode(String bindCode) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>().lambda().eq(UserInfo::getBindCode, bindCode);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        return userInfo.getMobile();
    }
}
